import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-10-13
 * Time: 22:25
 */
//此处这个类的属性的名字, 和json的key要保持一致
//这里的属性是public或者是提供public的getter方法
class Student{
    public int classId;
    public int studentId;
}

@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //假设客户端发来的请求形如 /studentInfo?classId=104&studentId=20
        //可以通过getParameter方法来拿到这两个id值
        resp.setContentType("text/html; charset=utf8");
        String queryString = req.getQueryString();
        String classId = req.getParameter("classId");
        String studentId = req.getParameter("studentId");
        System.out.println("classId:" + classId + " studentId:" + studentId);
        resp.getWriter().write("classId:" + classId + " studentId:" + studentId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf8");
        //获取body中的参数
        //预定body使用application/x-www-form-urlencoded这种格式来传参
        //其实这个格式和query string相同. 只是数据是在body中
//        String classId = req.getParameter("classId");
//        String studentId = req.getParameter("studentId");
//        System.out.println("classId:" + classId + " studentId:" + studentId);
//        resp.getWriter().write("classId:" + classId + " studentId:" + studentId);

        //处理JSON格式的请求
        ObjectMapper objectMapper = new ObjectMapper();
        //从请求的body中进行读取并解析
        //使用readValue来把json字符串转成Java对象
        //第一个参数是一个String或者是一个InputStream
        //第二个参数是转换的结果对应的Java类对象
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        System.out.println(student.classId +"," + student.studentId);
        resp.getWriter().write(student.classId +"," + student.studentId);
    }
}
